<%--
  Created by IntelliJ IDEA.
  User: mafh
  Date: 2017/6/8 0008
  Time: 09:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page pageEncoding="UTF-8" %>
<%!
    /**
     * 获取所有的标签（分页）
     * @param input
     * @return
     */
    public Message tagQuery(Input input){
        Message msg = new Message();
        Integer hospital = input.getInt("hospital",-999);
        Integer pageNum = input.getInt("page_num",1);//当前页，从1开始
        Integer itemCount = 7;//记录条数
        Map dataMap = new HashMap();
        //获取标签类别，基础标签和扩展标签分开取出
        List<Map> basicTagList = QBuilder.db("basedb").select("new map(id as id ,name as name)").from("hospital_label_category").where(new Where("hospital=0").and("status=",STATUS_ENABLE)).query().getResultObj();
        dataMap.put("basic",basicTagList);
        String categoryStr = "0";
        if(basicTagList.size()>0){
            StringBuffer sb = new StringBuffer(basicTagList.get(0).get("id")+"");
            for (int i = 1; i <basicTagList.size() ; i++) {
                sb.append(","+basicTagList.get(i).get("id"));
            }
            categoryStr = sb.toString();
        }
        List<Map> extendedTagList = QBuilder.db("basedb").select("new map(id as id,name as name,alias as alias,create_time as create_time)").from("hospital_label").where(new Where("hospital=",hospital).and("status=",STATUS_ENABLE).and("category not in ("+categoryStr+")")).page(itemCount,pageNum).order("id","asc").query().getResultObj();
        //获取扩展标签总页数
        List<Long> totalNumList = QBuilder.db("basedb").select("count(*)").from("hospital_label").where(new Where("hospital=",hospital).and("status=",STATUS_ENABLE).and("category not in ("+categoryStr+")")).query().getResultObj();
        Long totalNum = totalNumList.get(0);
        dataMap.put("extend",extendedTagList);
        dataMap.put("total_page",((totalNum-1)/itemCount)+1);
        msg.put("data",dataMap);
        return msg;
    }
    /**
     * 新建扩展标签
     */
    public Message tagAdd(Input input){
        Message msg = new Message();
        String tagName = input.getDesc("tag_name","");//标签名称
        String tagAlias = input.getDesc("tag_alias","");//标签备注
        Integer hospital = input.getInt("hospital",-999);
        //基础数据判断
        if(tagName.length()<2||tagName.length()>10){
            msg.setErrcodeAndErrmsg(23333,"标签名称为2~10位");
            return msg;
        }
        if(tagAlias.length()>50){
            msg.setErrcodeAndErrmsg(23333,"备注不能多于50位");
            return msg;
        }
        //标签名判重
        List<Map> tagIdList = QBuilder.db("basedb").select().from("hospital_label").where(new Where("hospital=",hospital).and("category=0").and("name='"+tagName+"'")).query().getResultObj();
        if(tagIdList.size()>0){//存在同名记录
            Map tagMap = tagIdList.get(0);
            if((tagMap.get("status")+"").equals("1")){//正在使用，驳回新建请求
                msg.setErrcodeAndErrmsg(23333,"标签名已被占用");
            }else{//删除了，恢复
                tagMap.put("status",STATUS_ENABLE);
                tagMap.put("alias",tagAlias);
                tagMap.put("create_time",System.currentTimeMillis());
                try{
                    DBTools.db("basedb").modItem("hospital_label",tagMap);
                }catch (Exception e){
                    e.printStackTrace();
                    msg.setErrcodeAndErrmsg(23333,"标签更新失败");
                }
            }
        }else{//不存在，直接存储
            //存储标签
            Map tagMap = new HashMap();
            tagMap.put("name",tagName);
            tagMap.put("hospital",hospital);
            tagMap.put("category",0);
            tagMap.put("create_time",System.currentTimeMillis());
            tagMap.put("json","{}");
            tagMap.put("alias",tagAlias);
            tagMap.put("status",STATUS_ENABLE);
            Serializable tagKey = DBTools.db("basedb").addItem("hospital_label",tagMap);
            if(tagKey == null){//存储失败
                msg.setErrcodeAndErrmsg(23333,"标签存储失败");
            }
        }
        return msg;
    }

    /**
     * 删除标签，前提是必须清空标签中的人
     */
    public Message tagDel(Input input){
        Message msg = new Message();
        Integer hospital = input.getInt("hospital",-999);
        Integer tagId = input.getInt("tag_id",0);
        //首先查询该标签下是否还有人
        List<Integer> userIdList = QBuilder.db("basedb").select("id").from("hospital_label_member").where(new Where("hospital=",hospital).and("label_id=",tagId).and("status=",STATUS_ENABLE)).query().getResultObj();
        if(userIdList.size()>0){//存在，没有删除干净，不允许删除
            msg.setErrcodeAndErrmsg(23333,"该标签不为空，请先删除该标签下的成员再删除标签");
        }else{//无数据，逻辑删除操作
            try{
                QBuilder.db("basedb").execHQL("update hospital_label set status="+STATUS_DISABLE+" where hospital="+hospital+" and id="+tagId);
            }catch (Exception e){
                e.printStackTrace();
                msg.setErrcodeAndErrmsg(23333,"标签更新失败");
            }
        }
        return msg;
    }

    /**
     *  标签修改
     * @param input
     * @return
     */
    public Message tagEdit(Input input){
        Message msg = new Message();
        Integer hospital = input.getInt("hospital",-999);
        Integer tagId = input.getInt("tag_id",0);
        String tagName = input.getDesc("tag_name","");//标签名称
        String tagAlias = input.getDesc("tag_alias","");//标签备注
        //标签名判重
        List<Map> tagIdList = QBuilder.db("basedb").select().from("hospital_label").where(new Where("hospital=",hospital).and("category=0").and("name=",tagName).and("id !=",tagId)).query().getResultObj();
        if(tagIdList.size()>0) {//存在同名记录
            Map tagMap = tagIdList.get(0);
            if ((tagMap.get("status") + "").equals("1")) {//正在使用，驳回修改请求
                msg.setErrcodeAndErrmsg(23333, "标签名已被占用");
                return msg;
            }
        }
        //更新当前记录
        try{
            Integer num = QBuilder.db("basedb").execHQL("update hospital_label set name='"+tagName+"',alias='"+tagAlias+"' where hospital="+hospital+" and id="+tagId);
            if(num > 0){//成功
                msg.put("data",num);
            }else{
                msg.setErrcodeAndErrmsg(23333,"标签修改失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            msg.setErrcodeAndErrmsg(23333,"标签修改异常");
        }
        return msg;
    }
    /**
     * 根据label标签id获取人员
     */
    public Message tagList(Input input){
        Message msg = new Message();
        Integer hospital = input.getInt("hospital",-999);
        Integer tagId = input.getInt("tag_id",0);
        Map dataMap = new HashMap();
        //查询科室，type=2
        List<Map> deptList = QBuilder.db("basedb").select("new map(d.id as id,d.deptName as deptName)").from("hospital_label_member lm,Dept d").where(new Where("lm.member_id=d.id").and("lm.type=2").and("lm.label_id=",tagId).and("lm.hospital=",hospital).and("lm.status=",STATUS_ENABLE).and("d.hospital=",hospital).and("d.status=",STATUS_ENABLE)).query().getResultObj();
        dataMap.put("dept",deptList);
        //查询人员,type=1
        List<Map> userList = QBuilder.db("basedb").select("new map(u.id as id,u.name as name,u.avatar as avatar)").from("hospital_label_member lm,hospital_user u").where(new Where("lm.type=1").and("lm.member_id=u.id").and("lm.label_id=",tagId).and("lm.hospital=",hospital).and("lm.status=",STATUS_ENABLE).and("u.hospital=",hospital).and("u.status=",STATUS_ENABLE)).query().getResultObj();
        //获取人员所在科室列表
        for(Map userMap:userList){
            List<Map> userDeptList = QBuilder.db("basedb").select("new map(d.id as id,d.deptName as deptName)").from("hospital_dept_user du,Dept d").where(new Where("du.dept_id=d.id").and("du.user_id=",userMap.get("id")+"").and("du.hospital=",hospital).and("du.status=",STATUS_ENABLE).and("d.hospital=",hospital).and("d.status=",STATUS_ENABLE)).query().getResultObj();
            userMap.put("deptList",userDeptList);
        }
        dataMap.put("user",userList);
        msg.put("data",dataMap);
        return msg;
    }

    /**
     * 新增成员
     * @param input
     * @return
     */
    public Message tagUserAdd(Input input){
        Message msg = new Message();
        String userStr = input.getDesc("user","");//人员列表
        String deptStr = input.getDesc("dept","");//科室列表
        Integer tagId = input.getInt("tag_id",0);
        Integer hospital = input.getInt("hospital",-999);
        List<Map> tagUserAddList = new ArrayList<>();
        List<Map> tagUserModList = new ArrayList<>();
        Map tagUserMap;
        if(!userStr.equals("")){//不为空，则进行下一步
            String[] userArray = userStr.split(",");
            //获取已有成员list
            List<Map> userList = QBuilder.db("basedb").select().from("hospital_label_member").where(new Where("hospital=",hospital).and("type=1").and("status=",STATUS_ENABLE).and("label_id=",tagId)).query().getResultObj();
            for(String userId:userArray){
                //检查是否已存在
                boolean checkFlag = false;
                for(Map userMap:userList){
                    if((userMap.get("member_id")+"").equals(userId)){//存在
                        if((userMap.get("status")+"").equals("0")){//逻辑删除了，加入modify中去
                            userMap.put("status",STATUS_ENABLE);
                            tagUserModList.add(userMap);
                        }
                        checkFlag = true;
                        break;
                    }
                }
                if(checkFlag){
                    continue;
                }
                tagUserMap = new HashMap();
                tagUserMap.put("label_id",tagId);
                tagUserMap.put("member_id",Integer.valueOf(userId));
                tagUserMap.put("type",1);
                tagUserMap.put("hospital",hospital);
                tagUserMap.put("json","{}");
                tagUserMap.put("create_time",System.currentTimeMillis());
                tagUserMap.put("status",STATUS_ENABLE);
                tagUserAddList.add(tagUserMap);
            }
        }
        if(!deptStr.equals("")) {//不为空，则进行下一步
            String[] deptArray = deptStr.split(",");
            //获取已有部门list
            List<Map> deptList = QBuilder.db("basedb").select().from("hospital_label_member").where(new Where("hospital=",hospital).and("status=",STATUS_ENABLE).and("type=2").and("label_id=",tagId)).query().getResultObj();
            for(String deptId:deptArray){
                //检查是否已存在
                boolean checkFlag = false;
                for(Map deptMap:deptList){
                    if((deptMap.get("member_id")+"").equals(deptId)){//存在
                        if((deptMap.get("status")+"").equals("0")){//逻辑删除了，加入modify中去
                            deptMap.put("status",STATUS_ENABLE);
                            tagUserModList.add(deptMap);
                        }
                        checkFlag = true;
                        break;
                    }
                }
                if(checkFlag){
                    continue;
                }
                tagUserMap = new HashMap();
                tagUserMap.put("label_id",tagId);
                tagUserMap.put("member_id",Integer.valueOf(deptId));
                tagUserMap.put("type",2);
                tagUserMap.put("hospital",hospital);
                tagUserMap.put("json","{}");
                tagUserMap.put("create_time",System.currentTimeMillis());
                tagUserMap.put("status",STATUS_ENABLE);
                tagUserAddList.add(tagUserMap);
            }
        }
        if(!tagUserAddList.isEmpty()){//不为空进行修改操作
            try{
                DBTools.db("basedb").modItem("hospital_label_memeber",tagUserModList);
            }catch (Exception e){
                e.printStackTrace();
                msg.setErrcodeAndErrmsg(23333,"更新操作失败");
                return msg;//直接返回，不进行存储操作
            }
        }
        if(!tagUserAddList.isEmpty()){//不为空进行存储操作
            List<Integer> keyList = DBTools.db("basedb").addItem("hospital_label_member",tagUserAddList);
            if(keyList.isEmpty()){
                msg.setErrcodeAndErrmsg(23333,"新增成员失败");
            }else{
                msg.put("data",keyList);
            }
        }
        return msg;
    }

    /**
     * 移除成员
     */
    public Message tagUserDel(Input input){
        Message msg = new Message();
        String userStr = input.getDesc("user","");//人员列表
        String deptStr = input.getDesc("dept","");//科室列表
        Integer tagId = input.getInt("tag_id",0);//标签id
        Integer hospital = input.getInt("hospital",-999);
        //直接批量操作
        if(userStr.equals("")&&deptStr.equals("")){//均为空，不操作数据库

        }else{
            //人员列表和科室列表判空操作
            userStr = userStr.equals("") ? "0" : userStr;
            deptStr = deptStr.equals("") ? "0" : deptStr;
            Integer num = QBuilder.db("basedb").execHQL("update hospital_label_member set status="+STATUS_DISABLE+" where label_id="+tagId+" and ((type=1 and member_id in ("+userStr+")) or (type=2 and member_id in ("+deptStr+")))");
            if(num <= 0){//修改数据库失败
                msg.setErrcodeAndErrmsg(23333,"移除失败，请在刷新后重试");
            }else{
                msg.put("data",num);
            }
        }
        return msg;
    }

    /**
     * 获取职位或职位子标签
     * @param input
     * @return
     */
    public Message tagSubList(Input input){
        Message msg = new Message();
        Integer hospital = input.getInt("hospital",-999);
        Integer tagId = input.getInt("tag_id",0);
        List<Map> dutyList = QBuilder.db("basedb").select("new map(id as id,name as name,alias as alias)").from("hospital_label").where(new Where("hospital=",hospital).and("status=",STATUS_ENABLE).and("category=",tagId)).query().getResultObj();
        msg.put("data",dutyList);
        return msg;
    }

%>

